using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Htse.Blue.Logic;
using Htse.Blue.Models;
using Htse.Blue.Logic.Validation;
using Htse.Blue.Models.ViewModels;

namespace Htse.Blue.Controllers
{
	[HandleError(Order = 0)]
	public class CityDistanceController : Controller
	{
		private ICityDistanceService _cityDistanceService;

		public CityDistanceController()
		{
			_cityDistanceService = new CityDistanceService(new ModelStateWrapper<CityDistance>(ModelState));
		}

		public CityDistanceController(
			ICityDistanceService cityDistanceService)
		{
			_cityDistanceService = cityDistanceService;
		}

		[Authorize]
		public ActionResult List(int? page, string sort, string filter)
		{
			int pageSize = SiteConstants.GetPreferredPageSizeOrDefault(Session);

			var cityDistances = _cityDistanceService.GetAll(
				page, pageSize, sort, filter);

			if (Request.IsAjaxRequest())
			{
				return PartialView("GridCityDistanceList", cityDistances);
			}
			else
			{
				return View("List", cityDistances);
			}
		}

		[Authorize]
		public ActionResult Create()
		{
			return View("Create", new CityDistance());
		}

		[Authorize]
		[ValidateAntiForgeryToken]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Create([Bind(Exclude = "Id")] CityDistance cityDistance)
		{
			bool result = _cityDistanceService.Create(cityDistance);

			if (result)
			{
				return RedirectToAction("List");
			}
			else
			{
				return View("Create", cityDistance);
			}
		}

		[Authorize]
		public ActionResult Edit(int id)
		{
			var cityDistance = _cityDistanceService.GetById(id);

			if (cityDistance == null)
			{
				return View("NotFound");
			}

			return View("Edit", cityDistance);
		}

		[Authorize]
		[ValidateAntiForgeryToken]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(CityDistance cityDistance)
		{
			var cityDistanceToEdit = _cityDistanceService.GetById(cityDistance.Id);

			cityDistanceToEdit.Distance = cityDistance.Distance;

			bool result = _cityDistanceService.Update(cityDistanceToEdit);

			if (result)
			{
				return RedirectToAction("List");
			}
			else
			{
				return View("Edit", cityDistanceToEdit);
			}
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		[AcceptVerbs(HttpVerbs.Delete)]
		[ActionName("Delete")]
		public ActionResult AjaxDelete(int id)
		{
			var cityDistanceToDelete = _cityDistanceService.GetById(id);

			if (cityDistanceToDelete == null)
			{
				return View("NotFound");
			}

			_cityDistanceService.Delete(cityDistanceToDelete);

			return List(null, string.Empty, string.Empty);
		}
	}
}
